/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.dialect;

import java.lang.reflect.Method;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.jianggujin.dbfly.mybatis.JConfiguration;
import com.jianggujin.dbfly.mybatis.builder.JParamConsts;
import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.entity.JEntityColumn;
import com.jianggujin.dbfly.mybatis.util.JElementBuilder;
import com.jianggujin.dbfly.mybatis.util.JProviderHelper;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * 批量插入，使用insert into XX() values (), ()形式
 * 
 * @author jianggujin
 *
 */
public class JInsertValuesHandler {

    /**
     * 处理批量插入，返回{@code true}表示支持并处理，{@code false}表示不支持
     * 
     * @param configuration
     * @param mapperClass
     * @param method
     * @param document
     * @param mapperElement
     * @param entity
     * @return
     */
    public boolean handleInsertList(JConfiguration configuration, Class<?> mapperClass, Method method,
            Document document, Element mapperElement, JEntity entity) {
        Element insertElement = JElementBuilder.buildInsertElement(document, method);
        String item = "item";
        JProviderHelper.insertIntoTable(configuration, document, insertElement, entity,
                JStringUtils.format("{}[0]", JParamConsts.PARAM_RECORD));
        JElementBuilder.appendChild(document, insertElement, JStringUtils.format("({}) VALUES ",
                JProviderHelper.getAllColumns(entity, JEntityColumn::isInsertable)));

        Element foreachElement = JElementBuilder.buildForeachElement(document, JParamConsts.PARAM_RECORD, item, ",");
        JProviderHelper.selectKeys(document, foreachElement, entity, item);
        JProviderHelper.bindGeneratorValues(document, foreachElement, entity, item);
        JElementBuilder.appendChild(document, foreachElement,
                JStringUtils.format("({})", JProviderHelper.getAllValues(entity, item, JEntityColumn::isInsertable)));
        insertElement.appendChild(foreachElement);
        mapperElement.appendChild(insertElement);
        return true;
    }
}
